﻿#region Usings
using System;
using System.Collections;
using System.Reflection;
using FluentNHibernate;
using FluentNHibernate.Framework;
using NetScrum.Infrastructure.NHibernate;
using NetScrum.Model.Repository;
using NetScrum.Model.Repository.Impl;
using NHibernate;
using NHibernate.Cfg;
using Microsoft.Practices.Unity;
#endregion

namespace NetScrum.Model.Factories
{
    /// <summary>
    /// Factory used to construct Repositories and inject all the dependencies needed
    /// </summary>
    public static class RepositoryFactory
    {
        private static IUnityContainer _repositoryMapping;

        static RepositoryFactory()
        {
            _repositoryMapping = new UnityContainer();
            _repositoryMapping.RegisterType<ProjectRepository, ProjectRepositoryNHibernate>();
            _repositoryMapping.Configure<InjectedMembers>()
                .ConfigureInjectionFor<ProjectRepositoryNHibernate>(
                    new InjectionConstructor(CreateNHibernateSession())
                    );
        }
        
        /// <summary>
        /// Creates an instance of a repository type
        /// </summary>
        /// <typeparam name="T">Type of the repository to be created</typeparam>
        /// <returns>Concrete implementation of the repository</returns>
        public static T CreateRepository<T>()
        {
            T rep = _repositoryMapping.Resolve<T>();
            return rep;         
        }
        
        private static ISession CreateNHibernateSession()
        {
            //TODO: While in the beggining, simple connection management will be used
            Configuration cfg = new Configuration().Configure();
            PersistenceModel m = new PersistenceModel();
            m.addMappingsFromAssembly(Assembly.Load("NetScrum.Core"));
            m.Configure(cfg);

            ISessionSource _source = new NHibernateSessionSource(m);
            ISession _session = _source.CreateSession();            
            _session.Clear();

            return _session;
        }
    }
}
